package com.qf.dao.impl;

import com.qf.dao.UserDao;
import com.qf.model.Card;
import com.qf.model.User;
import com.qf.utils.DruidUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.sql.Connection;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

public class UserDaoImpl extends BaseDao implements UserDao {
    QueryRunner queryRunner=new QueryRunner(DruidUtil.getDataSource());

    //检查身份证是否已注册
    @Override
    public User findUserByU_idcard(String u_idcard) {
        String sql = "select * from user where u_idcard = ?";
        return queryForOne(User.class,sql,u_idcard);
    }

    //添加注册的新用户
    @Override
    public int addUser(String u_phone,String u_pwd,String u_idcard,String u_name) {
        String sql = "insert into user (u_name,u_phone,u_pwd,u_idcard) values(?,?,?,?)";
        int update = update(sql,u_name,u_phone,u_pwd,u_idcard);
        return update;
    }

    //根据用户id查询用户信息
    @Override
    public User findByUid(int uid) {
        String sql="select * from user where u_id = ?";
        return queryForOne(User.class,sql,uid);
    }
//检查手机号是否已注册
    @Override
    public User findUserByphone(String phone) {
        String sql = "select * from user where u_phone = ?";
        return queryForOne(User.class,sql,phone);
    }

    //根据用户id修改app余额
    @Override
    public int updateUserBalance(User user) {
        String sql="update user set u_balance=u_balance-? where u_id=?";
        return update(sql,user.getU_balance(),user.getU_id());
    }

    //根据id修改用户身份证号信息 事务
    @Override
    public int updateUserIdCard(Connection connection, int u_id, String u_name, String u_idcard) {
        try {
            String sql = "update user set u_name = ?,u_idcard = ? where u_id = ?";
            int update = queryRunner.update(sql,u_name,u_idcard,u_id);
            return update;
        }catch (Exception e){
            e.printStackTrace();
        }
        return 0;
    }
    //根据用户id查询银行卡信息

    @Override
    public List<Card> findCardByUid(int uid) {
        String sql = "select * from card where u_id=? and ( c_check=1 or c_check=0 ) ";
        return  queryForList(Card.class,sql,uid);
    }

    //个人信息  修改

    @Override
    public int updateUserByUid(int uid, String u_sex, String u_email, String u_address, String pwd) {
        if(pwd==""){
            String  sql = "update user set u_sex=?,u_email=?,u_address=? where u_id=?";
            return  update(sql,u_sex,u_email,u_address,uid);
        }else {
            String  sql = "update user set u_sex=?,u_email=?,u_address=?,u_pwd=? where u_id=?";
            return  update(sql,u_sex,u_email,u_address,pwd,uid);
        }

    }
}
